﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace KidsProtector.DataAccess
{
    public class User
    {
        public bool CreateUser(string name, string mail, string pass, DateTime birthday)
        {
            T_User user = new T_User();
            user.Name = name;
            user.Mail = mail;
            user.Pass = pass;
            user.Birthday = birthday;
            return CreateUser(user);
        }

        public bool CreateUser(T_User user)
        {
            try
            {
                KidsProtectorEntities model = new KidsProtectorEntities();
                model.AddToT_User(user);
                model.SaveChanges();
                return true;
            }
            catch(Exception)
            {
                return false;
            }
        }

        public bool ModifyUser(long id, string name, string mail, string pass, DateTime birthday)
        {
            try
            {
                KidsProtectorEntities model = new KidsProtectorEntities();
                T_User user = model.T_User.Where(x=>x.Id == id).FirstOrDefault();
                if (name != "" && name != user.Name)
                    user.Name = name;
                if (mail != "" && mail != user.Mail)
                    user.Mail = mail;
                if (pass != "" && pass != user.Pass)
                    user.Pass = pass;
                if (birthday.Equals(user.Birthday) == false)
                    user.Birthday = birthday;
                model.SaveChanges();
                return true;
            }
            catch(Exception)
            {
                return false;
            }
        }
        public T_User Authentification(string mail, string pass)
        {
            try
            {
                KidsProtectorEntities model = new KidsProtectorEntities();
                T_User user = model.T_User.Where(x => x.Mail == mail && x.Pass == pass).FirstOrDefault();
                return user;
            }
            catch (Exception)
            {
                return null;
            }
        }
        public List<T_User> GetList()
        {
            List<T_User> list;
            try
            {
                KidsProtectorEntities model = new KidsProtectorEntities();
                list = model.T_User.ToList();
            }
            catch (Exception)
            {
                list = new List<T_User>();
            }

            return list;
        }

        public string GetMail(long idUser)
        {
            List<T_User> list = GetList();
            list.Remove(list.Where(x => x.Id == idUser).FirstOrDefault());
            Random r = new Random((int)DateTime.Now.Ticks);
            return list[r.Next(0, list.Count)].Mail;
        }
    }
}

